package com.coffee.aliyun.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.AddDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class DNSUtils {
	private static Properties properties=null;
	private static IAcsClient client = null;
	static{
		init();
	}
	
	public static void main(String[] args) {
		try {
			String ip=getIp();
			
			File file=new File("old_ip.lock");
			if (file.exists()) {
				BufferedReader reader = new BufferedReader(new FileReader(file));
				String oldIp=reader.readLine();
				reader.close();
				if (ip.equals(oldIp)) {
					return;
				}else{
					//ip不相同， 写入当前ip到文件
					FileWriter fw=new FileWriter(file);
					fw.write(ip);
					fw.flush();
					fw.close();
				}
			}else{
				//不存在， 写入当前ip到文件
				FileWriter fw=new FileWriter(file);
				fw.write(ip);
				fw.flush();
				fw.close();
			}
			String domainNamesStr = properties.getProperty("DomainName");
			
			String [] domainNames = domainNamesStr.split(";");
			
			for (String domainName : domainNames) {
				
				String rrString=properties.getProperty("RecordsDomain_"+domainName);
				String[] rr=rrString.split(";");
				DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
				request.setActionName("DescribeDomainRecords");
				request.setDomainName(domainName);
				
				DescribeDomainRecordsResponse response= client.getAcsResponse(request);
				List<Record> result=response.getDomainRecords();
				for (String rR : rr) {
					Record temp=null;
					for (Record record : result) {
						if (rR.equals(record.getRR())) {
							//存在解析记录
							temp=record;
							break;
						}
					}
					if (temp==null) {
						//不存在解析记录，新增
						addRecord(domainName, rR, ip);
						System.out.println("新增记录成功--"+domainName+"--"+rR+"--"+ip);
					}else{
						//存在解析记录，更新
						updateRecord(temp.getRecordId(), rR, ip);
						System.out.println("更新记录成功--"+temp.getDomainName()+"--"+rR+"--"+ip);
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String getIp() throws IOException{
		String url = "https://www.baidu.com/s?wd=%E6%9F%A5%E8%AF%A2ip&ie=utf-8&tn=02049043_27_pg";
		Connection conn = Jsoup.connect(url).header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
		Document document = conn.get();
		/*     */     
		Elements center = document.getElementsByClass("c-gap-right");
		String ip = ((Element)center.get(0)).text();
		int start = 6;
		ip = ip.substring(start);
		return ip;
	} 
	private static void init(){
		InputStream in = DNSUtils.class.getResourceAsStream("/system.properties");
		properties= new Properties();
    	try {
    		 properties.load(in);
    		 String regionId = "cn-hangzhou"; //必填固定值，必须为“cn-hanghou”
	         String accessKeyId = properties.getProperty("accessKeyId"); // your accessKey
	         String accessKeySecret = properties.getProperty("accessKeySecret");// your accessSecret
	         IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
	         // 若报Can not find endpoint to access异常，请添加以下此行代码
	         // DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Alidns", "alidns.aliyuncs.com");  
	         client = new DefaultAcsClient(profile);
    	}catch(Exception e){
    		System.exit(0);
    	}
	}
	private static void addRecord(String domainName,String rR,String value){
		try {
			AddDomainRecordRequest request=new AddDomainRecordRequest();
			request.setActionName("AddDomainRecord");
			request.setDomainName(domainName);
			request.setRR(rR);
			request.setType("A");
			request.setValue(value);
			client.getAcsResponse(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static void updateRecord(String recordId,String rR,String value){
		try {
			UpdateDomainRecordRequest request=new UpdateDomainRecordRequest();
			request.setActionName("UpdateDomainRecord");
			request.setRecordId(recordId);
			request.setRR(rR);
			request.setType("A");
			request.setValue(value);
			client.getAcsResponse(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
